<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="测评卷标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入测评卷标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测评卷类型" prop="title" style="width: 200px;">
        <el-select v-model="queryParams.type" placeholder="请选择测评卷类型" clearable>
          <el-option
              v-for="dict in exam_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="测评卷id" align="center" prop="id" v-if="false"/>
      <el-table-column label="测评卷标题" align="center" prop="title"/>
      <el-table-column label="测评卷封面" align="center" prop="paperImage">
        <template v-slot:default="scope">
          <el-image
              style="width: 200px; height: 100px"
              :src="scope.row.paperImage"
              :preview-src-list="[scope.row.paperImage]"
              v-if="scope.row.paperImage"
              fit="contain"
          >
          </el-image>
          <el-tag type="danger" v-else>暂无封面</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="测评卷描述" align="center" prop="description">
        <template v-slot:default="scope">
          <dict-tag :options="exam_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="测评卷描述" align="center" prop="type"/>
      <el-table-column label="题目总数" align="center" prop="questionTotal"/>
      <el-table-column label="开始时间" align="center" prop="startTime"/>
      <el-table-column label="结束时间" align="center" prop="endTime"/>
      <el-table-column label="限制时间（分钟）" align="center" prop="timeLimit">
        <template #default="scope">
          {{ scope.row.timeLimit }}
          <el-tag v-if="scope.row.timeLimit" type="success" style="margin-right: 1px;">分钟</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="isPublished">
        <template #default="scope">
          <el-switch
              v-model="scope.row.isPublished"
              active-text="发布"
              inactive-text="未发布"
              active-value="1"
              inactive-value="0"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="发布者" align="center" prop="publishedBy"/>
      <el-table-column label="发布时间" align="center" prop="publishedTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改测评卷管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="paperRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="测评卷标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入测评卷标题"/>
        </el-form-item>
        <el-form-item label="测评卷描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入测评卷描述"/>
        </el-form-item>
        <el-form-item label="测评卷类型" prop="type">
          <el-select v-model="form.type" type="textarea" placeholder="请选择测评卷类型">
            <el-option
                v-for="dict in exam_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              value-format="YYYY-MM-DD HH:mm:ss"
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="computeLimitTime"
              @clear="removeTimeLimit"
              :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="答题时间" prop="timeLimit" v-show="timeLimitFlag">
          <el-input disabled v-model="form.timeLimit" style="max-width: 150px">
            <template #suffix>
              <el-tag type="info">分钟</el-tag>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="测评卷封面" prop="paperImage">
          <image-upload v-model="form.paperImage"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Paper">
import {addPaper, changePaperStatus, delPaper, getPaper, listPaper, updatePaper} from "@/api/exam/paper";
import ImageUpload from "@/components/ImageUpload/index.vue";
import DictTag from "@/components/DictTag/index.vue";

const {proxy} = getCurrentInstance();
const {exam_type} = proxy.useDict("exam_type");

const paperList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const timeRange = ref(null); // 测评时间范围
const timeLimitFlag = ref(false); // 是否显示答题时间

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
  },
  rules: {
    title: [
      {required: true, message: "测评卷标题不能为空", trigger: "blur"},

    ],
    /*timeRange:[
      {required: true, message: "测评时间不能为空", trigger: "blur"}
    ],*/
    type: [
      {required: true, message: "测评卷类型不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 查询测评卷管理列表 */
function getList() {
  loading.value = true;
  listPaper(queryParams.value).then(response => {
    console.log("测评卷列表数据：", response)
    paperList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    paperImage: null,
    description: null,
    startTime: null,
    endTIme: null,
    timeLimit: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("paperRef");
}

// 修改发布状态
function handleStatusChange(row) {
  let text = row.isPublished === "1" ? "发布" : "取消发布";
  proxy.$modal.confirm('确认要"' + text + '""' + row.title + '"测评吗?').then(function () {
    return changePaperStatus(row.id, row.startTime, row.isPublished);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
    getList();
  }).catch(function () {
    row.isPublished = row.isPublished === "0" ? "1" : "0";
  });
}

// 计算测评时间
function computeLimitTime() {
  if (timeRange.value) {
    form.value.startTime = timeRange.value[0]; // 开始时间
    form.value.endTime = timeRange.value[1];  // 结束时间
    // 设置答题时间
    form.value.timeLimit = Math.floor((new Date(form.value.endTime) - new Date(form.value.startTime)) / 60000);
    timeLimitFlag.value = true;
  } else {
    removeTimeLimit();
  }
}

// 移除测评限制时间
function removeTimeLimit() {
  timeLimitFlag.value = false;
  form.value.timeLimit = null;
  form.value.startTime = null;
  form.value.endTime = null;
  timeRange.value = null;
}

// 限制开始时间不能小于当前时间,不是当天时间
function disabledDate(date) {
  const today = new Date();
  today.setHours(0, 0, 0, 0); // 将今天的小时、分钟、秒和毫秒设置为0
  return date && date < today;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加测评卷管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPaper(_id).then(response => {
    form.value = response.data;
    timeRange.value = [response.data.startTime, response.data.endTime]
    open.value = true;
    title.value = "修改测评卷管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["paperRef"].validate(valid => {
    if (valid) {
      form.value.startTime = timeRange.value ? timeRange.value[0] : null
      form.value.endTime = timeRange.value ? timeRange.value[1] : null
      // 测评限制时间为endTime-startTime
      if (form.value.endTime && form.value.startTime) {
        form.value.timeLimit = Math.floor((new Date(form.value.endTime) - new Date(form.value.startTime)) / 60000);
      } else {
        form.value.timeLimit = null;
      }
      console.log("提交数据", form.value)
      if (form.value.id != null) {
        updatePaper(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPaper(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除测评卷管理编号为"' + _ids + '"的数据项？').then(function () {
    return delPaper(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('exam/paper/export', {
    ...queryParams.value
  }, `paper_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
})
</script>


<style scoped>

</style>
